package com.pz.art.service.impl;

import com.pz.art.domain.AssoMemberUnit;
import com.pz.art.domain.AssoUnitmemberRole;
import com.pz.art.mapper.AssoUnitmemberRoleMapper;
import com.pz.art.service.MemberService;
import com.pz.art.domain.AssoMember;
import com.pz.art.mapper.MemberMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
@Primary
public class MemberServiceImpl implements MemberService {

    private static final Logger log = LoggerFactory.getLogger(MemberServiceImpl.class);

    @Autowired
    protected MemberMapper memberMapper;

    @Autowired
    protected AssoUnitmemberRoleMapper unitmemberRoleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;
    @Override
    public List<AssoMember> selectAllMember(AssoMember member) {
            return memberMapper.selectAllMember(member);
    }

    @Override
    public AssoMember selectMemberByPhoneNo(String phone) {
        return memberMapper.selectMemberByPhoneNo(phone);
    }

    @Override
    public List<AssoMember> selectNormalAllMember(AssoMember member) {
        return memberMapper.selectNormalAllMember(member);
    }

    @Override
    public AssoMember selectMemberById(Integer id) {
        return null;
    }

    @Override
    public int insertMember(AssoMember assoMember) {
        return 0;
    }

    @Override
    public int updateMember(AssoMember assoMember) {
        return memberMapper.updateMember(assoMember);
    }

    /**
     * 查询会员
     *
     * @param id 会员主键
     * @return 会员
     */
    @Override
    public AssoMember selectAssoMemberById(Long id)
    {
        return memberMapper.selectAssoMemberById(id);
    }

    /**
     * 查询会员列表
     *
     * @param assoMember 会员
     * @return 会员
     */
    @Override
    public List<AssoMember> selectAssoMemberList(AssoMember assoMember)
    {
        return memberMapper.selectAssoMemberList(assoMember);
    }

    /**
     * 新增会员
     *
     * @param assoMember 会员
     * @return 结果
     */
    @Override
    public int insertAssoMember(AssoMember assoMember)
    {
        assoMember.setCreateTime(DateUtils.getNowDate());
        return memberMapper.insertAssoMember(assoMember);
    }

    /**
     * 修改会员
     *
     * @param assoMember 会员
     * @return 结果
     */
    @Override
    public int updateAssoMember(AssoMember assoMember)
    {
        assoMember.setUpdateTime(DateUtils.getNowDate());
        return memberMapper.updateAssoMember(assoMember);
    }

    /**
     * 批量删除会员
     *
     * @param ids 需要删除的会员主键
     * @return 结果
     */
    @Override
    public int deleteAssoMemberByIds(Long[] ids)
    {
        return memberMapper.deleteAssoMemberByIds(ids);
    }

    /**
     * 删除会员信息
     *
     * @param id 会员主键
     * @return 结果
     */
    @Override
    public int deleteAssoMemberById(Long id)
    {
        return memberMapper.deleteAssoMemberById(id);
    }

    @Override
    public List<AssoMember>  getAssomemberByUnitId(Long unit_id) {
        return memberMapper.getAssomemberByUnitId(unit_id);
    }

    @Override
    public int updateAssoMemberUnit(Long[] ids, Long unit_id) {
        try {
            int unit_boolean = 1;
            return memberMapper.updateAssoMemberUnit(ids,unit_id,unit_boolean);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int insertjoinAssomember(Long[] ids, Long unit_id,Long events_id) {
        return memberMapper.insertjoinAssomember(ids,unit_id,events_id);
    }

    @Override
    public List<AssoMember> getNotApplyMember(Long events_id, Long unit_id) {
        return Collections.emptyList();
    }

    @Override
    public String importNormalMember(List<AssoMember> normalList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(normalList) || normalList.size() == 0)
        {
            throw new ServiceException("导入会员单位数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AssoMember memberlist : normalList)
        {
            try
            {
                String password = configService.selectConfigByKey("sys.user.initPassword");
                memberlist.setPassword(SecurityUtils.encryptPassword(password));
                memberlist.setStatus(1);
                memberlist.setUnit_id(0);
                memberlist.setCreate_time(DateUtils.getNowDate());
                memberlist.setAccount(memberlist.getPhone());
                memberlist.setJoin_time(DateUtils.getNowDate());
                memberlist.setJoin_ip("0.0.0.0");
                memberlist.setUnit_boolean(2);
                //给定会员单位权限
                AssoUnitmemberRole assoUnitmemberRole = new AssoUnitmemberRole();
                assoUnitmemberRole.setRoleId(2L);
                // 验证是否存在这个手机号
                AssoMember u = memberMapper.getNormalByPhone(memberlist.getPhone());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, memberlist);
                    memberMapper.insertMember(memberlist);
                    assoUnitmemberRole.setUnitMemberId(Long.valueOf(memberlist.getId()));
                    unitmemberRoleMapper.insertAssoUnitmemberRole(assoUnitmemberRole);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + memberlist.getName() + " 导入成功");
                }
                // 如果已经存在，则更新数据 功能暂时废弃
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + memberlist.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 "  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
